//
//  ScreenCar.m
//  AutoHome
//
//  Created by wqh on 15-5-12.
//  Copyright (c) 2015年 Wqh. All rights reserved.
//

#import "ScreenCar.h"

#import "ScreenCarCell.h"
#import "BaseGrayView.h"
#import "SelectBrandView.h"
#import "CarOperationModel.h"
#import "BrandCarModel.h"
#import "QueryCarResult.h"

#define kScreenCarCellId @"ScreenCarCellId"

@interface ScreenCar ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic) UITableView *tableView;
@property (nonatomic) NSMutableArray *dataArr;
@property (nonatomic) UIView *headerView;
@property (nonatomic) UIButton *findButton;
@property (nonatomic) BaseGrayView *grayView;
@property (nonatomic) SelectBrandView *selectBrandView;
@property (nonatomic ) NSArray *carOperationInfo;
@property (nonatomic ) NSArray *carOperationTitle;
@property (nonatomic) NSMutableDictionary *queryCarInfoDict;
@property (nonatomic) NSMutableDictionary *queryCarListDict;

@property (nonatomic) NSMutableArray *resultInfo;

@end

@implementation ScreenCar

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self createHeaderView];
    [self createTableView];
    [self initData];
    [self initCarOperationInfo];
    [self createFindButton] ;
    
    [self createGrayView];
    [self createSelectBrandView];
    
}

- (void)createTableView {
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight-64-49)];
    self.tableView.contentSize = CGSizeMake(0, 1000);
    self.tableView.showsVerticalScrollIndicator = YES;
    
    [self.tableView registerNib:[UINib nibWithNibName:@"ScreenCarCell" bundle:nil] forCellReuseIdentifier:kScreenCarCellId];
    self.tableView.tableHeaderView = self.headerView    ;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
}

- (void)createGrayView {
    self.grayView = [[BaseGrayView alloc] initWithFrame:CGRectMake(0, 20, kScreenWidth, kScreenHeight-20)];
    [[[UIApplication sharedApplication].delegate window] addSubview:self.grayView];
}

- (void)createSelectBrandView {
    self.selectBrandView = [[[NSBundle mainBundle] loadNibNamed:@"SelectBrandView" owner:self options:nil] lastObject];
    self.selectBrandView.frame= CGRectMake(kScreenWidth, 20, kScreenWidth-50, kScreenHeight-20);
    [[[UIApplication sharedApplication].delegate window] addSubview:self.selectBrandView];
    __weak typeof(self) mySelf = self;
    
    self.grayView.myBlock = ^ {
        mySelf.selectBrandView.frame = CGRectMake(kScreenWidth, 20, kScreenWidth-50, kScreenHeight-20);
    };
    
    self.selectBrandView.myBlock = ^ {
        mySelf.grayView.alpha = 0;
    };
    
    self.selectBrandView.valueBlock = ^(CarOperationModel *model,NSInteger index) {
        NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithDictionary:mySelf.dataArr[index]];
        NSString *key = [[dict allKeys] firstObject];
        [dict setObject:model.name forKey:key];
        [mySelf.dataArr replaceObjectAtIndex:index withObject:dict];
        [mySelf.tableView reloadData];
       
        
        //是否显示 Label（删除清空条件)
        [mySelf displayDeleteFilter];
        
        
        //根据选中的信息 查找车系
        if ([model isKindOfClass:[BrandCarModel class]]) {//车牌
            [mySelf.queryCarInfoDict setObject:[[(BrandCarModel *)model id] stringValue] forKey:key];
        }else {//其它

            if ([key isEqualToString:@"价格"]) {
                NSString *price = model.value;
                
                NSArray *array = [price componentsSeparatedByString:@"|"];
                
                NSString *mipNum = array[0];
                NSString *mapNum = array[1];
                NSString *mip = [NSString stringWithFormat:@"%d",mipNum.integerValue*10000];
                NSString *map = [NSString stringWithFormat:@"%d",mapNum.integerValue*10000];
                
                
                [mySelf.queryCarInfoDict setObject:mip forKey:@"最低价格"];
                [mySelf.queryCarInfoDict setObject:map forKey:@"最高价格"];
            }else if([key isEqualToString:@"排量"]) {
                NSArray *array = [model.value componentsSeparatedByString:@"|"];
                NSString *mid = array[0];
                NSString *mad = array[1];
                [mySelf.queryCarInfoDict setObject:mid forKey:@"最低排量"];
                [mySelf.queryCarInfoDict setObject:mad forKey:@"最高排量"];
                
            }else {
                [mySelf.queryCarInfoDict setObject:model.value forKey:key];
            }
            
        }
        
        [mySelf queryCarList:mySelf.queryCarInfoDict];
        
 
    };
    self.selectBrandView.brandNameBlock = ^(NSString *brandName) {
        [mySelf.dataArr replaceObjectAtIndex:0 withObject:@{@"品牌":brandName}];
        [mySelf.tableView reloadData];
    };

}

- (void)displayDeleteFilter {
    for (NSDictionary *dict in self.dataArr) {
        NSString *key = [[dict allKeys] lastObject];
        if (![dict[key] isEqualToString:@"不限"]) {
            
            NSArray *arr =  self.headerView.subviews;
            for (UIView *view in arr) {
                if ([view isKindOfClass:[UIButton class]]) {
                    view.hidden = NO;
                }
            }
            
        }
    }
}

- (void)initData {
    self.dataArr = [NSMutableArray arrayWithArray:@[@{@"品牌":@"不限"},@{@"价格":@"不限"},@{@"级别":@"不限"},@{@"国别":@"不限"},@{@"变速箱":@"不限"},@{@"结构":@"不限"},@{@"排量":@"不限"},@{@"燃料":@"不限"},@{@"配置":@"不限"}]];
}

- (void)createFindButton {
    self.findButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.findButton.frame = CGRectMake(12, self.view.bounds.size.height-64-44-44, kScreenWidth - 12*2, 35);
    self.findButton.backgroundColor = [[UIColor alloc] initWithRed:56/255.0f green:105/255.0f blue:198/255.0f alpha:1];

    self.findButton.titleLabel.textAlignment = NSTextAlignmentCenter;
    
    [self.findButton addTarget:self action:@selector(findBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:self.findButton];
    
    self.queryCarInfoDict = [NSMutableDictionary dictionaryWithDictionary:@{@"品牌":@"0",@"最低价格":@"0",@"最高价格":@"0",@"级别":@"0",@"国别":@"0",@"变速箱":@"0",@"结构":@"0",@"最低排量":@"0",@"最高排量":@"0",@"燃料":@"0",@"配置":@"0"}];
    [self queryCarList:self.queryCarListDict];
    
}

- (void)findBtnClick:(UIButton *)button {
    QueryCarResult *vc = [QueryCarResult new];
    vc.queryFilterList = self.queryCarInfoDict;
    vc.resultInfo = self.resultInfo;
    if (self.myPageJumpBlcok) {
        self.myPageJumpBlcok(vc);
    }
    if (self.myHiddeTabBarBlock) {
        self.myHiddeTabBarBlock(YES);
    }
    self.tabBarController.tabBar.hidden = YES;
}

- (void)queryCarList:(NSDictionary *)dict {
    [[DataEngine sharedInstance] requestCarListWithDictionary:self.queryCarInfoDict pageIndex:1 Success:^(id respondsData) {
        
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:respondsData options:NSJSONReadingMutableContainers error:nil];
        self.queryCarListDict = dict[@"result"];
        [self chageFindButtonTitle:self.queryCarListDict[@"rowcount"] total:self.queryCarListDict[@"totalspeccount"]];
    } failed:^(NSError *error) {
        
    }];
}

- (void)chageFindButtonTitle:(NSNumber *)systemCount total:(NSNumber*)totalCount {
    self.resultInfo = [NSMutableArray arrayWithArray:@[systemCount,totalCount]];
    if ([systemCount.stringValue isEqualToString:@"0"]) {
        [self.findButton setTitle:@"未找到符合条件的车系" forState:UIControlStateNormal];
        return;
    }
    [self.findButton setTitle:[NSString stringWithFormat:@"共%@个车系%@个车型",systemCount.stringValue,totalCount.stringValue] forState:UIControlStateNormal];
}

- (void)createHeaderView {
    self.headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 35)];
    self.headerView.backgroundColor = [UIColor customGrayColor];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, 60, 24)];
    label.font = [UIFont systemFontOfSize:13];
    label.text = @"筛选条件";
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    [button setTitle:@"清空条件" forState:UIControlStateNormal];
    [button setImage:[UIImage imageNamed:@"bar_btn_icon_shut"] forState:UIControlStateNormal];
    button.titleEdgeInsets = UIEdgeInsetsMake(0, -22, 0, 0);
    button.frame = CGRectMake(kScreenWidth-120, 5, 100, 24);
    button.titleLabel.font = [UIFont systemFontOfSize:14];
    button.hidden = YES;
    [button addTarget:self action:@selector(deleteFilter:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.headerView addSubview:label];
    [self.headerView addSubview:button];
}

- (void)deleteFilter:(UIButton *)button {
    button.hidden = YES;
    self.dataArr = [NSMutableArray arrayWithArray:@[@{@"品牌":@"不限"},@{@"价格":@"不限"},@{@"级别":@"不限"},@{@"国别":@"不限"},@{@"变速箱":@"不限"},@{@"结构":@"不限"},@{@"排量":@"不限"},@{@"燃料":@"不限"},@{@"配置":@"不限"}]];
    [self.tableView reloadData];
    self.queryCarInfoDict = [NSMutableDictionary dictionaryWithDictionary:@{@"品牌":@"0",@"最低价格":@"0",@"最高价格":@"0",@"级别":@"0",@"国别":@"0",@"变速箱":@"0",@"结构":@"0",@"最低排量":@"0",@"最高排量":@"0",@"燃料":@"0",@"配置":@"0"}];
    [self queryCarList:self.queryCarListDict];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ScreenCarCell *cell = [tableView dequeueReusableCellWithIdentifier:kScreenCarCellId  forIndexPath:indexPath];
    
    NSDictionary *dict = self.dataArr[indexPath.row];
    NSString *key = [[dict allKeys] firstObject];
    
    cell.titleLabel.text = key;
    if ([key isEqualToString:@"品牌"] && ![dict[key] isKindOfClass:[NSString class]] ) {
        BrandCarModel *model = dict[key];
        cell.contentLabel.text = model.name;
        
    }else {
        cell.contentLabel.text = [dict objectForKey:key];
    }
    
    
    
    if ([cell.contentLabel.text isEqualToString:@"不限"]) {
        cell.contentLabel.textColor = [UIColor lightGrayColor];
    }else {
        cell.contentLabel.textColor = [UIColor customBlueColor];
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [UIView animateWithDuration:0.5 animations:^{
        self.grayView.alpha = 0.5;
        self.selectBrandView.frame = CGRectMake(50, 20, kScreenWidth-50, kScreenHeight-20);
        
        [self postData:indexPath];
        
        NSDictionary *dict =  self.dataArr[indexPath.row];
        NSString *key = [[dict allKeys] firstObject];
        if ([key isEqualToString:@"品牌"] && ![dict[key] isKindOfClass:[NSString class]] ) {
            BrandCarModel *model = dict[key];
            self.selectBrandView.carOperation = model.name;
            
        }else {
            self.selectBrandView.carOperation = [dict objectForKey:key];
        }
        //向selectBrandView发送更新视图的通知;
        [[NSNotificationCenter defaultCenter] postNotificationName:@"updateSelectBrandView" object:nil];
    } completion:^(BOOL finished) {
       
    }];
    
}

- (void)initCarOperationInfo {
    self.carOperationInfo = @[@"price",@"level",@"country",@"gearbox",@"structure",@"displacement",@"fueltype",@"configs"];
    self.carOperationTitle = @[@"价格",@"级别",@"国别",@"变速箱",@"结构",@"排量",@"燃料",@"配置"];
}

- (void)postData:(NSIndexPath *)indexPath {
    
    if (indexPath.row == 0) {
        self.selectBrandView.dataArr = [NSMutableArray arrayWithArray:[[DataEngine sharedInstance] parseBrandData]];
        self.selectBrandView.title = @"选择品牌";
    }else {
        
        self.selectBrandView.dataArr = [[NSMutableArray alloc] init];
        
        for (CarOperationModel *model in [[[DataEngine sharedInstance] parseCarOperationData] objectForKey:self.carOperationInfo[indexPath.row-1]]) {
            [self.selectBrandView.dataArr addObject:model];
        }
        self.selectBrandView.title = self.carOperationTitle[indexPath.row-1];
        
    }
    
}



/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
